简单易用的json解析包gjson

今天逛github,发现一个有趣的json解析包。

它的规则有点像jquery 那样的规则,来定位到值,并获取。

这个包是: https://github.com/tidwall/gjson

同样,搬来官网示例:

package main

import "github.com/tidwall/gjson"

const json = `{"name":{"first":"Janet","last":"Prichard"},"age":47}`

func main() {
	value := gjson.Get(json, "name.last")
	println(value.String())
}

它通过name.last 就可以获取到last 的值

再来看更多的例子,挺有趣的:

{
  "name": {"first": "Tom", "last": "Anderson"},
  "age":37,
  "children": ["Sara","Alex","Jack"],
  "fav.movie": "Deer Hunter",
  "friends": [
    {"first": "Dale", "last": "Murphy", "age": 44},
    {"first": "Roger", "last": "Craig", "age": 68},
    {"first": "Jane", "last": "Murphy", "age": 47}
  ]
}

"name.last"          >> "Anderson"
"age"                >> 37
"children"           >> ["Sara","Alex","Jack"]
"children.#"         >> 3
"children.1"         >> "Alex"
"child*.2"           >> "Jack"
"c?ildren.0"         >> "Sara"
"fav\.movie"         >> "Deer Hunter"
"friends.#.first"    >> ["Dale","Roger","Jane"]
"friends.1.last"     >> "Craig"

这里,可以使用#[...] 来匹配数组第一项 或 #[...]# 来匹配所有项,支持的操作符有 ==, !=, <, <=, >, >= ,%

friends.#[last=="Murphy"].first    >> "Dale"
friends.#[last=="Murphy"]#.first   >> ["Dale","Jane"]
friends.#[age>45]#.last            >> ["Craig","Murphy"]
friends.#[first%"D*"].last         >> "Murphy"

这套规则,如果使用在反射,用来做一些结构体的查询,感觉,也是很不错的。

humboldt Written by:

humboldt 的趣味程序园